module.exports = class extends think.Model {
  async list({ fid, module, pageSize = 10, pageNum = 1 }) {
    const where = {};
    if (module) where.module = module;
    if (fid !== undefined && fid !== null && fid !== "") where.fid = fid || 0;
    const data = await this.where(where)
      .page(pageNum, pageSize)
      .countSelect();
    return data;
  }

  /**
   * 获得树形结构
   * @param fid
   * @returns {Promise<void>}
   */
  async tree(fid) {
    const list = await this.where({ fid }).select();
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      if ((await this.hasChildren(item.id)) > 0) {
        item.children = await this.tree(item.id);
      }
    }
    return list;
  }

  /**
   *
   * @param id
   * @returns {Promise<void>}
   */
  async hasChildren(id) {
    const count = await this.where({ fid: id }).count();
    return count;
  }

  async detail({ id, url, type = "detail" }) {
    let data;
    if (id) data = await this.find(id);
    else if (url) data = await this.where({ url }).find();
    if (type === "tree") {
      data.children = await this.tree(id || data.id);
    }
    return data;
  }
};
